package org.hitchhike.web.front.controller;

import javax.servlet.http.HttpServletRequest;

import org.hitchhike.common.domain.BaseEntity;
import org.hitchhike.common.web.controller.BaseController;
import org.hitchhike.core.domain.User;
import org.hitchhike.core.exception.BaseException;
import org.hitchhike.core.form.SafetyForm;
import org.hitchhike.core.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "/front")
public class SafetyController extends BaseController<BaseEntity, Long> {

  @Autowired
  private UserService userService;

  @RequestMapping(value = "/safety", method = RequestMethod.GET)
  public String safety(Model model) {
    User user = userService
        .findByUsername(SecurityContextHolder.getContext().getAuthentication().getName());
    model.addAttribute("user", user);
    model.addAttribute("safety", "active");
    return viewName("safety");
  }

  @RequestMapping(value = "/safety/save", method = RequestMethod.POST)
  public String save(SafetyForm safetyForm, HttpServletRequest request) {
    User user = userService
        .findByUsername(SecurityContextHolder.getContext().getAuthentication().getName());

    if (user == null) {
      throw new BaseException("用户不存在。。。");
    } else if (!user.getPassword().equals(safetyForm.getOldPassword())) {
      throw new BaseException("原密码错误。。。");
    } else if (!safetyForm.getNewPassword().equals(safetyForm.getRePassword())) {
      throw new BaseException("新密码不一致。。。");
    }

    user.setPassword(safetyForm.getNewPassword());

    try {
      userService.update(user);
    } catch (Exception e) {
      throw new BaseException(e.getMessage());
    }

    return redirectToUrl(viewName("safety"));
  }

}
